package top.flvio.middleware.dynamic;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import top.flvio.middleware.DBContextHolder;
import top.flvio.middleware.annotation.DBRouterStrategy;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: Mybatis拦截器,通过对SQL语句拦截处理，修改分表信息
 * @author: flvio
 * @date: 2025/2/5
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DynamicMybatisPlugin implements Interceptor
{
    private Pattern pattern = Pattern.compile("(from|into|update)[\\s]{1,}(\\w{1,})",Pattern.CASE_INSENSITIVE);

    @Override
    public Object intercept(Invocation invocation) throws Throwable
    {
        //获取StatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
        MappedStatement mappedStatement = (MappedStatement)metaObject.getValue("delegate.mappedStatement");

        //获取自定义注解判断是否分表操作
        String id = mappedStatement.getId();
        String className = id.substring(0, id.lastIndexOf("."));
        Class<?> clazz = Class.forName(className);
        DBRouterStrategy dbRouterStrategy = clazz.getAnnotation(DBRouterStrategy.class);
        if(null == dbRouterStrategy || !dbRouterStrategy.splitTable()){
            return invocation.proceed();
        }

        //获取sql

        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        String sql = boundSql.getSql();

        //替换USER表名 为 USER_03
        Matcher matcher = pattern.matcher(sql);

        String tableName = null;

        if(matcher.find()){
            tableName = matcher.group().trim();
        }

        assert null != tableName;
        String replaceSql = matcher.replaceAll(tableName + "_" + DBContextHolder.getTbKey());

        //通过反射修改sql语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        try
        {
            field.setAccessible(true);
            field.set(boundSql,replaceSql);
        }catch (Exception e){
            throw e;
        }finally
        {
            field.setAccessible(false);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target)
    {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties)
    {
        Interceptor.super.setProperties(properties);
    }

}
